package com.fone.player.storage;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import com.fone.player.entity.OfflineCache;
import com.fone.player.util.L;

/**
 * 
 * 缓存文件夹表适配器
 * 
 * @author wangyang
 * @since 2014年4月29日
 */
public class OfflineCacheFolderDataBaseAdapter implements IFoneDatabase {
	private static final String TAG = OfflineCacheFolderDataBaseAdapter.class
			.getSimpleName();
	private static final OfflineCacheFolderDataBaseAdapter mInstance = new OfflineCacheFolderDataBaseAdapter();
	private OperateDataBaseTemplate mGeneralDataBaseTemplate = OperateDataBaseTemplate
			.getInstance();

	private OfflineCacheFolderDataBaseAdapter() {

	}

	public static OfflineCacheFolderDataBaseAdapter getInstance() {
		return mInstance;
	}

	/**
	 * 
	 * 添加缓存条目
	 * 
	 * @param offlineCache
	 *            缓存条目
	 * @return int 插入结果<br>
	 *         1 成功 <br>
	 *         -1 插入异常
	 * 
	 */
	public int addOfflineCacheFolder(SQLiteDatabase sqliteDatabase,
			List<OfflineCache> offlineCacheList) {
		synchronized (TAG) {

			// 创建文件夹sql语句
			StringBuilder sql = new StringBuilder();
			sql.append("insert or ignore into ")
					.append(TB_OFFLINE_CACHE_FOLDER).append(" (");
			sql.append(OFFLINE_CACHE_FOLDER_CID).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_CCID).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_VIDEO_ID).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_NAME).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_IMAGE_URL).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_EPISODE_NUM).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_EPISODE_UPDATE_INFO).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_CONTENT_TYPE).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_XYZPLAY_URL).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_DRAMA_URL).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_SOURCE_NAME).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_CREATE_TIME);
			sql.append(") values(?,?,?,?,?,?,?,?,?,?,?,?);");

			try {
				sqliteDatabase.beginTransaction();
				SQLiteStatement fileStatement = sqliteDatabase
						.compileStatement(sql.toString());

				for (OfflineCache offlineCache : offlineCacheList) {
					fileStatement.bindLong(1, offlineCache.getCacheCID());
					fileStatement.bindLong(2, offlineCache.getCacheCCID());
					fileStatement.bindLong(3, offlineCache.getCacheVideoId());
					fileStatement.bindString(4, offlineCache.getCacheName());
					fileStatement
							.bindString(5, offlineCache.getCacheImageUrl());
					// 选集编号,文件夹层级暂时不赋值
					fileStatement.bindString(6, "");
					fileStatement.bindString(7,
							offlineCache.getCacheEpisodeUpdateInfo());
					fileStatement.bindLong(8,
							offlineCache.getCacheContentType());
					fileStatement.bindString(9,
							offlineCache.getCacheXYZPlayUrl());
					fileStatement.bindString(10,
							offlineCache.getCacheDramaUrl());
					fileStatement.bindString(11,
							offlineCache.getCacheSourceName());
					fileStatement.bindLong(12, System.currentTimeMillis());
					fileStatement.executeInsert();
				}

				sqliteDatabase.setTransactionSuccessful();

			} catch (Exception e) {
				if (e != null) {
					e.printStackTrace();
					L.e(TAG, "addOfflineCacheFolder", e.getMessage());
				}

				return -1;
			} finally {
				sqliteDatabase.endTransaction();
			}
			return 1;
		}
	}

	/**
	 * 
	 * 添加缓存条目
	 * 
	 * @param offlineCache
	 *            缓存条目
	 * @return int 插入结果<br>
	 *         1 成功 <br>
	 *         -1 插入异常
	 * 
	 */
	public int addOfflineCacheFolder(List<OfflineCache> offlineCacheList) {
		synchronized (TAG) {

			// 创建文件夹sql语句
			StringBuilder sql = new StringBuilder();
			sql.append("insert or ignore into ")
					.append(TB_OFFLINE_CACHE_FOLDER).append(" (");
			sql.append(OFFLINE_CACHE_FOLDER_CID).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_CCID).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_VIDEO_ID).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_NAME).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_IMAGE_URL).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_EPISODE_NUM).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_EPISODE_UPDATE_INFO).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_CONTENT_TYPE).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_XYZPLAY_URL).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_DRAMA_URL).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_SOURCE_NAME).append(",");
			sql.append(OFFLINE_CACHE_FOLDER_CREATE_TIME);
			sql.append(") values(?,?,?,?,?,?,?,?,?,?,?,?);");

			try {
				mGeneralDataBaseTemplate.open();
				mGeneralDataBaseTemplate.beginTransaction();

				SQLiteStatement fileStatement = mGeneralDataBaseTemplate
						.getSQLiteStatement(sql.toString());

				for (OfflineCache offlineCache : offlineCacheList) {
					fileStatement.bindLong(1, offlineCache.getCacheCID());
					fileStatement.bindLong(2, offlineCache.getCacheCCID());
					fileStatement.bindLong(3, offlineCache.getCacheVideoId());
					fileStatement.bindString(4, offlineCache.getCacheName());
					fileStatement
							.bindString(5, offlineCache.getCacheImageUrl());
					// 选集编号,文件夹层级暂时不赋值
					fileStatement.bindString(6, "");
					fileStatement.bindString(7,
							offlineCache.getCacheEpisodeUpdateInfo());
					fileStatement.bindLong(8,
							offlineCache.getCacheContentType());
					fileStatement.bindString(9,
							offlineCache.getCacheXYZPlayUrl());
					fileStatement.bindString(10,
							offlineCache.getCacheDramaUrl());
					fileStatement.bindString(11,
							offlineCache.getCacheSourceName());
					fileStatement.bindLong(12, System.currentTimeMillis());
					mGeneralDataBaseTemplate.insert(fileStatement);
				}

				mGeneralDataBaseTemplate.setTransactionSuccessful();

			} catch (Exception e) {
				if (e != null) {
					e.printStackTrace();
					L.e(TAG, "addOfflineCacheFolder", e.getMessage());
				}

				return -1;
			} finally {
				mGeneralDataBaseTemplate.endTransaction();
				mGeneralDataBaseTemplate.close();
			}
			return 1;
		}
	}

	/**
	 * 
	 * 判断此对象是否在缓存表中
	 * 
	 * @return OfflineCache 缓存对象
	 */
	public OfflineCache getOfflineCache(OfflineCache offlineCache) {
		switch (offlineCache.getCacheHierarchyType()) {
		case OfflineCache.CACHE_HIERARCHY_FOLDER:
			// 文件夹不显示勾选
			offlineCache.setCacheIsDownlaod(false);
			break;
		case OfflineCache.CACHE_HIERARCHY_FILE:
			offlineCache = OfflineCacheFileDataBaseAdapter.getInstance()
					.getOfflineCacheByCID(offlineCache);
			break;
		default:
			break;
		}

		return offlineCache;
	}

	/**
	 * 
	 * 获得缓存文件夹集合(已获得下载进度信息)
	 * 
	 * @return ArrayList<OfflineCache> 缓存文件夹集合
	 */
	public ArrayList<OfflineCache> getOfflineCacheFolderList() {
		StringBuilder sql = new StringBuilder("select * from ");
		sql.append(TB_OFFLINE_CACHE_FOLDER);
		sql.append(" order by ");
		sql.append(OFFLINE_CACHE_FOLDER_CREATE_TIME);
		sql.append(" desc");
		ArrayList<OfflineCache> offlineCacheList = null;
		Cursor cursor = null;
		try {
			mGeneralDataBaseTemplate.open();
			cursor = mGeneralDataBaseTemplate.select(sql.toString());

			if (cursor == null) {
				return null;
			}

			// 读取数据
			offlineCacheList = new ArrayList<OfflineCache>();
			while (cursor.moveToNext()) {
				OfflineCache offlineCacheFolder = getOfflineCacheFolderByCursor(cursor);

				if (offlineCacheFolder != null) {

					offlineCacheList.add(offlineCacheFolder);

				}
			}

		} catch (Exception e) {
			if (e != null) {

				L.e(TAG, "getOfflineCacheList", "e" + e);

			}
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			mGeneralDataBaseTemplate.close();
		}

		return offlineCacheList;
	}

	/**
	 * 
	 * 根据缓存Id列表删除缓存文件夹 <br>
	 * 同步方法
	 * 
	 * @param offlineCacheFolderList
	 *            缓存文件夹列表
	 * @return int 操作结果<br>
	 *         1 删除成功<br>
	 *         -1 删除异常<br>
	 */
	public int deleteOfflineCacheFolderByCCID(
			List<OfflineCache> offlineCacheFolderList) {
		int result = 1;
		try {

			mGeneralDataBaseTemplate.open();
			mGeneralDataBaseTemplate.beginTransaction();
			for (OfflineCache offlineCacheFolder : offlineCacheFolderList) {
				if (offlineCacheFolder.getCacheCCID() == 0) {
					L.e(TAG, "deleteOfflineCacheFolderByCCID", "ccid=0");
				}
				StringBuilder where = new StringBuilder();
				where.append(OFFLINE_CACHE_FOLDER_CCID);
				where.append("=?");
				mGeneralDataBaseTemplate.delete(TB_OFFLINE_CACHE_FOLDER, where
						.toString(), new String[] { String
						.valueOf(offlineCacheFolder.getCacheCCID()) });
			}
			mGeneralDataBaseTemplate.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
			result = -1;
		} finally {

			mGeneralDataBaseTemplate.endTransaction();
			mGeneralDataBaseTemplate.close();
		}
		return result;
	}

	/**
	 * 
	 * 删除空文件夹<br>
	 * 同步方法
	 * 
	 * @return int 操作结果<br>
	 *         1 删除成功<br>
	 *         -1 删除异常<br>
	 */
	public int deleteOfflineCacheFolder() {
		int result = 1;
		try {
			mGeneralDataBaseTemplate.open();
			StringBuilder deleteSql = new StringBuilder();
			deleteSql.append("delete from ").append(TB_OFFLINE_CACHE_FOLDER);
			deleteSql.append(" where ");
			deleteSql.append(OFFLINE_CACHE_FOLDER_CCID).append(" in ");
			deleteSql.append("(select ");
			deleteSql.append(OFFLINE_CACHE_FOLDER_CCID).append(" from ");
			deleteSql.append(TB_OFFLINE_CACHE_FOLDER).append(" where ");
			deleteSql.append(OFFLINE_CACHE_FOLDER_CCID).append(" not in ");
			deleteSql.append("(select ");
			deleteSql.append(OFFLINE_CACHE_FILE_CCID).append(" from ");
			deleteSql.append(TB_OFFLINE_CACHE_FILE).append("))");
			mGeneralDataBaseTemplate.delete(deleteSql.toString());
		} catch (Exception e) {
			result = -1;
		} finally {
			mGeneralDataBaseTemplate.close();
		}
		return result;
	}

	/**
	 * 
	 * 删除所有文件夹<br>
	 * 同步方法
	 * 
	 * @return int 操作结果<br>
	 *         1 删除成功<br>
	 *         -1 删除异常<br>
	 */
	public int deleteOfflineCacheFolderALL() {
		int result = 1;
		try {

			StringBuilder sql = new StringBuilder();
			sql.append("delete from ").append(TB_OFFLINE_CACHE_FOLDER);
			mGeneralDataBaseTemplate.open();
			mGeneralDataBaseTemplate.delete(sql.toString());

		} catch (Exception e) {
			result = -1;
		} finally {
			mGeneralDataBaseTemplate.close();
		}
		return result;
	}

	/**
	 * 
	 * 根据游标读取字段信息
	 * 
	 * @param cursor
	 * @return OfflineCache
	 */
	private OfflineCache getOfflineCacheFolderByCursor(Cursor cursor) {
		OfflineCache offlineCacheFolder = new OfflineCache();
		offlineCacheFolder.setCacheCID(cursor.getLong(cursor
				.getColumnIndex(OFFLINE_CACHE_FOLDER_CID)));
		offlineCacheFolder.setCacheCCID(cursor.getLong(cursor
				.getColumnIndex(OFFLINE_CACHE_FOLDER_CCID)));
		offlineCacheFolder.setCacheVideoId(cursor.getLong(cursor
				.getColumnIndex(OFFLINE_CACHE_FOLDER_VIDEO_ID)));
		offlineCacheFolder.setCacheName(cursor.getString(cursor
				.getColumnIndex(OFFLINE_CACHE_FOLDER_NAME)));
		offlineCacheFolder.setCacheImageUrl(cursor.getString(cursor
				.getColumnIndex(OFFLINE_CACHE_FOLDER_IMAGE_URL)));
		offlineCacheFolder.setCacheEpisodeUpdateInfo(cursor.getString(cursor
				.getColumnIndex(OFFLINE_CACHE_FOLDER_EPISODE_UPDATE_INFO)));
		offlineCacheFolder.setCacheContentType(cursor.getInt(cursor
				.getColumnIndex(OFFLINE_CACHE_FOLDER_CONTENT_TYPE)));
		offlineCacheFolder.setCacheXYZPlayUrl(cursor.getString(cursor
				.getColumnIndex(OFFLINE_CACHE_FOLDER_XYZPLAY_URL)));
		offlineCacheFolder.setCacheDramaUrl(cursor.getString(cursor
				.getColumnIndex(OFFLINE_CACHE_FOLDER_DRAMA_URL)));
		offlineCacheFolder.setCacheSourceName(cursor.getString(cursor
				.getColumnIndex(OFFLINE_CACHE_FOLDER_SOURCE_NAME)));
		offlineCacheFolder.setCacheCreateTime(cursor.getLong(cursor
				.getColumnIndex(OFFLINE_CACHE_FOLDER_CREATE_TIME)));
		// 替换文件夹为文件,界面就会出现文件夹和文件同时显示的效果
		switch (offlineCacheFolder.getCacheContentType()) {
		case OfflineCache.CACHE_CONTENT_TYPE_ANIMATION:
		case OfflineCache.CACHE_CONTENT_TYPE_TV:
		case OfflineCache.CACHE_CONTENT_TYPE_VARIETY:
			// 文件夹
			offlineCacheFolder
					.setCacheHierarchyType(OfflineCache.CACHE_HIERARCHY_FOLDER);
			break;
		default:
			// 文件
			offlineCacheFolder
					.setCacheHierarchyType(OfflineCache.CACHE_HIERARCHY_FILE);
		}

		return offlineCacheFolder;
	}

}